package com.test.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.test.pojo.Domain;
import com.test.service.DomainService;
import com.test.service.impl.DomainServiceImpl;
import com.test.util.ParameterUtil;
import com.test.util.Result;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/domain")
public class DomainServlet extends HttpServlet {

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ApplicationContext applicationContext = (ApplicationContext) (config.getServletContext().getAttribute("applicationContext"));
        this.domainService = applicationContext.getBean(DomainService.class);
    }

    private DomainService domainService;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String act = ParameterUtil.getString(request, "act");
        if ("edit".equals(act)) {//添加
            edit(request, response);
        } else if ("check".equals(act)) {//校验域名和端口是否存在
            check(request, response);
        } else if ("list".equals(act)) {
            list(request, response);
        } else if ("delete".equals(act)) {
            delete(request, response);
        } else if ("info".equals(act)) {
            info(request, response);
        }
    }

    protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = ParameterUtil.getInteger(request, "id");
        Domain domain = domainService.getDomainById(id);
        request.setAttribute("domain", domain);
        request.getRequestDispatcher("edit.jsp").forward(request, response);
    }

    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = ParameterUtil.getInteger(request, "id");
        //验证id不为空,略
        domainService.deleteDomainById(id);
        response.sendRedirect("/domain?act=list");
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String addr = ParameterUtil.getString(request, "addr");
        String ip = ParameterUtil.getString(request, "ip");
        Integer pageNum = ParameterUtil.getInteger(request, "pn");
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        Domain domain = new Domain();
        domain.setAddr(addr);
        domain.setIp(ip);
        PageInfo<Domain> pageInfo = domainService.getDomainList(domain, pageNum, 2);
        request.setAttribute("pageInfo", pageInfo);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }

    protected void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String addr = ParameterUtil.getString(request, "addr");
        Integer port = ParameterUtil.getInteger(request, "port");
        Integer id = ParameterUtil.getInteger(request, "id");
        //校验为空 略
//        if (ParameterUtil.checkParam(addr, request, "域名不能为空")
//                && ParameterUtil.checkParam(ip, request, "ip不能为空")
        Result res = domainService.checkAddrAndPort(addr, port);
        if (id != null && !res.isSuccess()) {//修改
            res.setSuccess(id.equals(res.getOther()));//验证已经存在的这条数据是不是要修改的这条
        }
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(res);
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }

    protected void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String addr = ParameterUtil.getString(request, "addr");
        String ip = ParameterUtil.getString(request, "ip");
        Integer port = ParameterUtil.getInteger(request, "port");
        Integer status = ParameterUtil.getInteger(request, "status");
        Integer id = ParameterUtil.getInteger(request, "id");
        if (ParameterUtil.checkParam(addr, request, "域名不能为空")
                && ParameterUtil.checkParam(ip, request, "ip不能为空")
                && ParameterUtil.checkParam(port, request, "端口不能为空")
                && ParameterUtil.checkParam(status, request, "状态不能为空")) {
            if (!ParameterUtil.checkIP(ip)) {
                request.setAttribute("message", "ip不合法");
                request.getRequestDispatcher("edit.jsp").forward(request, response);
                return;
            }
            Domain domain = new Domain(addr, port, status, ip);
            Result res = null;
            if (id == null) {//添加
                res = domainService.addDomain(domain);
            } else {//修改
                domain.setId(id);
                res = domainService.updateDomain(domain);
            }
            if (res.isSuccess()) {//添加成功，跳转列表
                //request.getRequestDispatcher("list.jsp").forward(request, response);
                response.sendRedirect("/domain?act=list");
            } else {
                request.setAttribute("message", res.getMessage());
                request.getRequestDispatcher("edit.jsp").forward(request, response);
            }
        } else {//参数校验没通过,返回到原来的界面
            request.getRequestDispatcher("edit.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}